import styles from './forget.module.less'
import Modal from '@/components/modal'
import Button from '@/components/button'
import Input from '@/components/input'
import { useCountDown } from 'ahooks'
import { useRef, useState, useEffect } from 'react'
import { getCode } from '@/api/user'
import { debounce } from 'lodash-es'
import Toast from '@/components/toast'

const Index = (props) => {
  const { visible, close, onConfirm, formInfo, setFormInfo } = props
  const submitRef = useRef()
  const [targetDate, setTargetDate] = useState(0)

  const [countdown] = useCountDown({
    targetDate,
  })

  const checkEmail = (email) => {
    const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ //优化邮箱校验
    return pattern.test(email)
  }

  //获取验证码
  const fetchCode = async () => {
    const isPass = checkEmail(formInfo.email)
    setFormInfo({ emailErr: !isPass })
    if (!isPass) {
      return
    }
    setTargetDate(Date.now() + 60000)
    const res = await getCode({ email: formInfo.email })
    if (!res.code) {
      Toast.normal('已发送验证码至邮箱，请查收')
    }
  }
  const debounceFetchCode = debounce(fetchCode, 100)
  const GetCodeDom = (
    <div className={styles.getCode}>
      {countdown ? (
        <span className={styles.wait}>{Math.round(countdown / 1000)}s后重发</span>
      ) : (
        <span className={styles.code} onClick={debounceFetchCode}>
          获取验证码
        </span>
      )}
    </div>
  )

  const onSubmit = async () => {
    const isValidEmail = checkEmail(formInfo.email)
    setFormInfo({
      emailErr: !isValidEmail,
      codeErr: !formInfo.code,
    })
    if (!isValidEmail || !formInfo.code) {
      return
    }
    onConfirm()
  }

  useEffect(() => {
    const down = (e) => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    window.addEventListener('keydown', down)
    return () => {
      window.removeEventListener('keydown', down)
    }
  }, [])

  return (
    <Modal visible={visible}>
      <div className={styles.pwd}>
        <h1 className={styles.title}>修改密码</h1>
        <img src="/images/close.webp" className={styles.close} onClick={close} />
        <p className={styles.inputLabel}>
          <span>邮箱</span>
          {formInfo.emailErr && <span>邮箱格式有误，请重新输入</span>}
        </p>
        <Input
          id="pwd"
          inputClass="input"
          placeholder="请输入邮箱"
          onChange={(e) => setFormInfo({ email: e.target.value })}
        />
        <p className={styles.inputLabel}>
          <span>验证码</span>
          {formInfo.codeErr && <span>验证码无效，请确认后重新输入</span>}
        </p>
        <Input
          inputClass="input"
          placeholder="请输入验证码"
          onChange={(e) => setFormInfo({ code: e.target.value })}
          suffix={GetCodeDom}
        />
        <Button ref={submitRef} onClick={onSubmit} className={styles.submit}>
          提交
        </Button>
      </div>
    </Modal>
  )
}

export default Index
